package com.zkingsoft.common.actions;

import static com.zkingsoft.common.constance.AppConstance.SAFEPATH;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.matrix.core.anotations.RemoveRequestToken;
import com.matrix.core.anotations.SaveRequestToken;
import com.matrix.core.constance.MatrixConstance;
import com.matrix.core.constance.SystemErrorCode;
import com.matrix.core.constance.SystemMessageCode;
import com.matrix.core.exception.GlobleException;
import com.matrix.core.pojo.AjaxResult;
import com.matrix.core.pojo.PaginationVO;
import com.matrix.core.tools.LogUtil;
import com.matrix.core.tools.PropertiesUtil;
import com.matrix.core.tools.WebUtil;
import com.matrix.core.web.BaseAction;
import com.zkingsoft.common.bean.SysUserLoginRecord;
import com.zkingsoft.common.bean.SysUsers;
import com.zkingsoft.common.constance.AppConstance;
import com.zkingsoft.common.constance.AppMessageCode;
import com.zkingsoft.common.constance.AppVocabularyCode;
import com.zkingsoft.common.dao.SysUsersDao;
import com.zkingsoft.common.service.SysUsersService;
import com.zkingsoft.common.tools.PasswordUtil;

/**
 * @description 公司管理员管理
 * @author 姜友瑶
 * @email 935090232@qq.com
 * @date 2016-06-26
 */
@Controller
@RequestMapping(value = "admin")
public class AdminAction extends BaseAction {

	@Autowired
	private SysUsersService sysUsersService;

	@Autowired
	private SysUsersDao usersDao;

	public static final String BEV = "SYSUSERS_BEV";

	/**
	 * 
	 * @Description: 页面定向方法，每个权限模块公用一个，每个模块共享一个一级路径，已便于进行权限过滤
	 * @author:姜友瑶
	 * @param page1
	 * @param page2
	 * @return 返回类型 String
	 * @date 2016年8月31日
	 */
	@RequestMapping(value = "/redirect/{page1}/{page2}")
	public String redirect(@PathVariable("page1") String page1, @PathVariable("page2") String page2) {
		return "admin/" + page1 + "/" + page2;
	}

	/**
	 * 
	 * @Description: 页面定向方法，每个权限模块公用一个，每个模块共享一个一级路径，已便于进行权限过滤
	 * @author:姜友瑶
	 * @param page1
	 * @param page2
	 * @return 返回类型 String
	 * @date 2016年8月31日
	 */
	@RequestMapping(value = "/redirect/{page1}")
	public String redirect(@PathVariable("page1") String page1) {
		return "admin/" + page1;
	}

	/**
	 * 列表显示
	 * 
	 * @author JIANGYOUYAO
	 * @email 935090232@qq.com
	 * @date Dec 10, 2017
	 * @param sysUsers
	 * @param pageVo
	 * @return
	 */
	@RequestMapping(value = SAFEPATH + "/showList")
	public @ResponseBody AjaxResult showList(SysUsers sysUsers, PaginationVO pageVo) {
		SysUsers user = WebUtil.getSessionAttribute(MatrixConstance.LOGIN_KEY);
		sysUsers.setCompanyId(user.getCompanyId());
		sysUsers.setSuUserType(AppConstance.USER_TYPE_EMPLOYEE);
		return showList(sysUsersService, sysUsers, pageVo);
	}

	/**
	 * 新增管理员
	 * 
	 * @author JIANGYOUYAO
	 * @email 935090232@qq.com
	 * @date Dec 10, 2017
	 * @param sysUsers
	 * @return
	 */
	@RemoveRequestToken
	@PostMapping(value = SAFEPATH + "/addAdmin")
	public @ResponseBody AjaxResult addAdmin(SysUsers sysUsers) {
		int i = sysUsersService.addAdmin(sysUsers);
		if (i > 0) {
			return new AjaxResult(AjaxResult.STATUS_SUCCESS, SystemMessageCode.ADD_SUCCES, AppVocabularyCode.ADMIN);
		} else {
			throw new GlobleException(SystemErrorCode.DATA_ADD_FAIL);
		}
	}

	/**
	 * 修改公司管理员
	 * 
	 * @author JIANGYOUYAO
	 * @email 935090232@qq.com
	 * @date Dec 10, 2017
	 * @param sysUsers
	 * @return
	 */
	@RemoveRequestToken
	@PostMapping(value = SAFEPATH + "/modifyAdmin")
	public @ResponseBody AjaxResult addOrModify(SysUsers sysUsers) {
		AjaxResult result = modify(sysUsersService, WebUtil.getSessionAttribute(BEV), sysUsers,
				AppVocabularyCode.ADMIN);
		WebUtil.removeSessionAttribute(BEV);
		return result;
	}

	@PostMapping(value =  "/modifyPhoto")
	public @ResponseBody AjaxResult modifyPhoto(String suPhoto) {
		SysUsers user = new SysUsers();
		String suId = ((SysUsers) getSessionUser()).getSuId();
		user.setSuId(suId);
		user.setSuPhoto(suPhoto);
		sysUsersService.modifyByModel(user);
		WebUtil.setSessionAttribute(MatrixConstance.LOGIN_KEY, sysUsersService.findById(suId));
		return new AjaxResult(AjaxResult.STATUS_SUCCESS, "头像更新成功");
	}

	/**
	 * 进入修改界面
	 * 
	 * @author JIANGYOUYAO
	 * @email 935090232@qq.com
	 * @date Dec 10, 2017
	 * @param id
	 * @return
	 */
	@SaveRequestToken
	@RequestMapping(value = SAFEPATH + "/editForm")
	public String editForm(String id) {
		SysUsers sysUsers;
		if (id != null) {
			sysUsers = sysUsersService.findById(id);
			WebUtil.getRequest().setAttribute("obj", sysUsers);
			WebUtil.setSessionAttribute(BEV, sysUsers);
		}
		return "admin/sys/admin-form";
	}

	/**
	 * 删除
	 * 
	 * @author JIANGYOUYAO
	 * @email 935090232@qq.com
	 * @date Dec 10, 2017
	 * @param keys
	 * @return
	 */
	@RequestMapping(value = SAFEPATH + "/del")
	public @ResponseBody AjaxResult del(String keys) {
		return remove(sysUsersService, keys);
	}

	/**
	 * 重置密码
	 * 
	 * @author JIANGYOUYAO
	 * @email 935090232@qq.com
	 * @date 2017年12月12日
	 * @param id
	 * @return
	 */
	@RequestMapping(value = SAFEPATH + "/resetPassword")
	public @ResponseBody AjaxResult resetPassword(String id) {

		SysUsers loginUser = getSessionUser();

		SysUsers user = sysUsersService.findById(id);
		if (user != null) {

			LogUtil.info("#{}进行重置{}的密码操作#", loginUser.getSuAccount(), user.getSuAccount());

			user.setSuPassword(PropertiesUtil.getString(AppConstance.DEFAULT_PASSWORD));
			try {
				// 设置加密后的密码
				user.setSuPassword(PasswordUtil.getEncrypUserPwd(user));
			} catch (UnsupportedEncodingException | NoSuchAlgorithmException e) {
				LogUtil.error("重置用户密码加密失败", e);
				throw new GlobleException(SystemErrorCode.SYSTEM_UNKNOW_ERROR);
			}
			sysUsersService.modifyByModel(user);
		} else {
			return new AjaxResult(AjaxResult.STATUS_FAIL, SystemErrorCode.INVALID_DATA, id);
		}
		return new AjaxResult(AjaxResult.STATUS_SUCCESS, AppMessageCode.Common.OPERATION_SUCCESS);
	}

	/**
	 * 账号锁定和解锁
	 * 
	 * @author JIANGYOUYAO
	 * @email 935090232@qq.com
	 * @date 2017年12月12日
	 * @param status
	 * @param id
	 * @return
	 */
	@RequestMapping(value = SAFEPATH + "/accountLock/{status}")
	public @ResponseBody AjaxResult lock(@PathVariable("status") String status, String id) {
		SysUsers user = sysUsersService.findById(id);
		switch (status) {
		case "unlock":
			sysUsersService.unlockUser(user.getSuAccount());
			break;
		case "lock":
			sysUsersService.lockUser(user.getSuAccount());
			break;
		default:
			return new AjaxResult(AjaxResult.STATUS_FAIL, SystemErrorCode.INVALID_DATA, status);
		}
		return new AjaxResult(AjaxResult.STATUS_SUCCESS, AppMessageCode.Common.OPERATION_SUCCESS);
	}

	/**
	 * 查询登录历史
	 * 
	 * @author JIANGYOUYAO
	 * @email 935090232@qq.com
	 * @date 2018年6月14日
	 * @param loginRecord
	 * @param pageVo
	 * @return
	 */
	@RequestMapping(value = "/showLoginRecordList")
	public @ResponseBody AjaxResult showLoginRecordList(SysUserLoginRecord loginRecord, PaginationVO pageVo) {
		if (pageVo == null) {
			pageVo = new PaginationVO();
		}
		SysUsers user = getSessionUser();
		// 非管理员只查询自己的登录记录
		if (!AppConstance.USER_TYPE_ADMIN.equals(user.getSuUserType())) {
			loginRecord.setUserAccount(user.getSuAccount());
		}
		List<SysUserLoginRecord> dataList = usersDao.selectLoginRecordList(loginRecord, pageVo);
		AjaxResult result = new AjaxResult(AjaxResult.STATUS_SUCCESS, dataList,
				usersDao.selectLoginRecordTotal(loginRecord));
		return result;
	}

	/**
	 * 进入修改界面
	 * 
	 * @author JIANGYOUYAO
	 * @email 935090232@qq.com
	 * @date 2018年3月6日
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/updatePassword")
	public @ResponseBody AjaxResult toUpdatePassword(String oldPassword, String newPassword) {

		SysUsers loginUser = getSessionUser();

		SysUsers user = sysUsersService.findById(loginUser.getSuId());

		SysUsers oldUser = new SysUsers();
		oldUser.setSuPassword(oldPassword);
		oldUser.setSuRegisterTime(user.getSuRegisterTime());
		try {
			oldUser.setSuPassword(PasswordUtil.getEncrypUserPwd(oldUser));
			// 旧密码比较
			if (oldUser.getSuPassword().equals(user.getSuPassword())) {
				LogUtil.info("#{}进行修改{}的密码操作#", loginUser.getSuAccount(), user.getSuAccount());
				user.setSuPassword(newPassword);

				// 设置加密后的密码
				user.setSuPassword(PasswordUtil.getEncrypUserPwd(user));

				sysUsersService.modifyByModel(user);

			} else {
				return new AjaxResult(AjaxResult.STATUS_FAIL, "旧密码不对");
			}

		} catch (UnsupportedEncodingException | NoSuchAlgorithmException e) {
			LogUtil.error("用户密码加密失败", e);
			throw new GlobleException(SystemErrorCode.SYSTEM_UNKNOW_ERROR);
		}

		return new AjaxResult(AjaxResult.STATUS_SUCCESS, "密码修改成功");
	}

}